<template>
  <div>
    <el-card>
      <div slot="header">
        <div class="flex-x justify-between items-center flex-wrap">
          <div class="flex-x gap-4 pt-2">
            <span v-if="showCourseSelect">
              <course-select v-model="query.courseId" @change="handleCourseChange"></course-select>
            </span>
            <span v-if="showCourseSelect">
              <course-section-select v-model="query.sectionId" :courseId="query.courseId"
                @change="handleSectionChange"></course-section-select>
            </span>
            <span v-if="showCourseSelect">
              <lesson-select v-model="query.lessonId" :courseId="query.courseId" :sectionId="query.sectionId"
                @change="handleLessonChange"></lesson-select>
            </span>
            <span>
              <tag-select v-model="query.tagIds" @change="handleTagChange"></tag-select>
            </span>
            <span>
              <vxe-input v-model="query.keyword" clearable :placeholder="'搜索习题内容'" size="medium"
                @keyup.enter.native="filterByKeyword"></vxe-input>
            </span>          
            <span>
              <el-button type="primary" plain size="small" @click="filterByKeyword" icon="el-icon-search"
                :loading="loading">搜索</el-button>
            </span>
          </div>
          <div class="flex-x">
            <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">
              添加习题
            </el-button>
          </div>
        </div>
      </div>

      <!-- Question Table -->
      <vxe-table stripe auto-resize :data="questionList" :loading="loading" :tree-config="{ children: 'children' }"
        :custom-config="tableCustomConfig" align="center" ref="table">
        <vxe-table-column field="id" title="ID" width="100" tree-node></vxe-table-column>
        <vxe-table-column field="courseAndSection" title="课程" width="200">
          <template v-slot="{ row }">
            <div v-if="row.lessonName" class="flex-y flex-center">
              <span>{{ row.courseName }}</span>
              <span> {{ row.sectionName }} - {{ row.lessonName }}</span>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="content" title="题目内容" align="left" min-width="200" show-overflow>
          <template v-slot="{ row }">
            <div class="flex-x items-center gap-2">
            <div>{{ row.content }}</div>
            <el-tooltip effect="dark" content="预览" placement="top">
              <el-button type="text" size="small" icon="el-icon-view" @click="handlePreview(row)">
              </el-button>
            </el-tooltip>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="type" title="题目类型" width="100" :visible="false">
          <template v-slot="{ row }">
            <el-tag :type="row.type === 1 ? 'primary' : 'success'" size="small">
              {{ row.type === 1 ? '单选题' : '多选题' }}
            </el-tag>
          </template>
        </vxe-table-column>
        <vxe-table-column field="answer" title="答案" width="100" :visible="false" />
        <vxe-table-column field="tags" title="标签" width="200">
          <template v-slot="{ row }">
            <el-tag v-for="tag in row.tags" :key="tag.id" size="small" class="mr-2">{{ tag.name }}</el-tag>
            <el-button v-if="!row.parentId" type="text" size="medium"
              :icon="`el-icon-${row.tags?.length > 0 ? 'edit' : 'plus'}`" @click="handleEditTags(row)"></el-button>
          </template>
        </vxe-table-column>
        <vxe-table-column field="isPublic" title="状态" width="80">
          <template v-slot="{ row }">
            <div class="flex-y flex-center">
              <el-switch v-model="row.isPublic" @change="handleChangeStatus(row, 'isPublic')" />
              <span class="font-10">{{ row.isPublic ? '公开' : '私密' }}</span>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="gmtCreate" title="创建时间" width="160">
          <template v-slot="{ row }">
            {{ formatDate(row.gmtCreate) }}
          </template>
        </vxe-table-column>
        <vxe-table-column title="操作" width="100" fixed="right">
          <template v-slot="{ row }">
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button plain circle type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button plain circle type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">
              </el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
      </vxe-table>

      <!-- Pagination -->
      <div class="flex-x justify-end items-center gap-4 mt-4">
        <el-pagination class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="query.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
        <el-button size="small" @click="showTableCustom" circle icon="el-icon-menu"></el-button>
      </div>

      <!-- Question Drawer -->
      <question-form-drawer ref="formDrawer" @success="handleSaveSuccess" />

      <TagSelectDialog ref="tagSelectDialog" v-model="currentRow.tags" @change="handleTagsChange"></TagSelectDialog>

      <QuestionPreviewDialog ref="questionPreviewDialog"></QuestionPreviewDialog>
    </el-card>
  </div>
</template>

<script>
import api from '@/common/api';
import CourseSelect from '@/components/admin/CourseSelect';
import CourseSectionSelect from "@/components/admin/CourseSectionSelect.vue";
import LessonSelect from "@/components/admin/LessonSelect.vue";
import Editor from '@/components/admin/Editor.vue';
import SortOrderEditor from '@/components/admin/SortOrderEditor.vue';
import TagSelectDialog from '@/components/admin/TagSelectDialog.vue';
import TagSelect from '@/components/admin/TagSelect.vue';
import { DEFAULT_TABLE_CUSTOM_CONFIG } from "@/common/constants";
import FormDrawer from '@/components/admin/FormDrawer.vue';
import QuestionFormDrawer from './components/QuestionFormDrawer.vue'
import Markdown from '@/components/oj/common/Markdown.vue';
import QuestionPreviewDialog from './components/QuestionPreviewDialog.vue';
import { pick } from 'xe-utils';

export default {
  name: 'QuestionList',
  components: {
    CourseSectionSelect,
    CourseSelect,
    LessonSelect,
    Editor,
    SortOrderEditor,
    TagSelectDialog,
    TagSelect,
    FormDrawer,
    QuestionFormDrawer,
    Markdown,
    QuestionPreviewDialog
  },
  props: {
    showCourseSelect: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      tableCustomConfig: DEFAULT_TABLE_CUSTOM_CONFIG,

      // List data
      questionList: [],
      loading: false,
      total: 0,
      query: {
        keyword: '',
        currentPage: 1,
        limit: 10,
        courseId: this.$route.query.courseId || null,
        sectionId: this.$route.query.sectionId || null,
      },
      currentRow: {},
      activeColumn: null,

    };
  },
  created() {
    this.getQuestionList();
  },
  methods: {
    // Get lesson list
    async getQuestionList() {
      try {
        this.loading = true;
        const { data } = await api.admin_getQuestionList({
          courseId: this.query.courseId,
          sectionId: this.query.sectionId,
          currentPage: this.query.currentPage,
          tagId: (this.query.tagIds || []).join(','),
          limit: this.query.limit,
          keyword: this.query.keyword
        });
        this.questionList = data.data.records;
        this.total = data.data.total;
      } catch (error) {
        this.$message.error('获取习题列表失败');
      } finally {
        this.loading = false;
      }
    },

    // Handle course change
    handleCourseChange(courseId) {
      this.query.currentPage = 1;
      this.query.sectionId = null;
      this.query.lessonId = null;
      this.getQuestionList();
    },

    handleSectionChange(sectionId) {
      this.query.currentPage = 1;
      this.query.lessonId = null;
      this.query.sectionId = sectionId;
      this.getQuestionList();
    },

    handleLessonChange(lessonId) {
      this.query.currentPage = 1;
      this.query.lessonId = lessonId;
      this.getQuestionList();
    },

    handleTagChange(tagIds) {
      console.log('tagIds', tagIds)
      this.query.tagIds = tagIds;
      this.getQuestionList();
    },

    showTableCustom() {
      console.log(this.$refs.table)
      this.$refs.table?.openCustom()
    },

    // Handle pagination
    handleSizeChange(val) {
      this.query.limit = val;
      this.getQuestionList();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getQuestionList();
    },
    handleEditTags(row) {
      this.currentRow = row
      const tagIds = row.tags?.map(tag => tag.id) || []
      this.$refs.tagSelectDialog.open(tagIds);
    },
    handlePreview(row) {
      this.$refs.questionPreviewDialog.open(row)
    },
    handleTagsChange(tagIds) {
      const data = {
        targetId: this.currentRow.id,
        targetType: 'question',
        tagIds
      }
      api.admin_saveTagRel(data).then(res => {
        this.$message.success('更新成功')
        this.getQuestionList()
      }).catch(error => {
        this.$message.error('更新失败')
      })
    },

    // Handle CRUD operations
    handleAdd() {
      const data = {
        courseId: this.query.courseId,
        sectionId: this.query.sectionId
      }
      this.$refs.formDrawer.open(data);
    },
    async handleEdit(row) {
      const data = { id: row.id }
      this.$refs.formDrawer.open(data);
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该习题?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await api.admin_deleteQuestion(row.id);
        this.$message.success('删除成功');
        this.getQuestionList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },
    async handleChangeStatus(row, field) {
      const data = pick(row, ['id', field])
      try {
        this.loading = true
        await api.admin_saveQuestion(data)
        this.$message.success('更新成功')
      } finally {
        this.loading = false
      }
    },

    async handleSortUpdate(row, newValue) {
      await api.admin_saveQuestion({
        id: row.id,
        sortOrder: newValue
      });
      this.getQuestionList();
    },

    // Form operations
    handleSaveSuccess() {
      this.getQuestionList()
    },

    // Filter operations
    filterByKeyword() {
      this.query.currentPage = 1;
      this.getQuestionList();
    },

    // Utils
    formatDate(date) {
      return date;
    },


  }
};
</script>

<style scoped>
:deep(.el-input__inner),
:deep(.vxe-input--inner) {
  height: 32px;
  line-height: 32px;
}
</style>
